package cc.chengheng.acl.service.impl;

import cc.chengheng.acl.entity.User;
import cc.chengheng.acl.service.PermissionService;
import cc.chengheng.acl.service.UserService;
import cc.chengheng.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询数据库
        User user = userService.selectByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        cc.chengheng.security.entity.User curUser = new cc.chengheng.security.entity.User();
        BeanUtils.copyProperties(user, curUser);

        // 根据用户查询用户的权限列表
        List<String> permissionValueList = permissionService.selectPermissionValueByUserId(user.getId());

        SecurityUser securityUser = new SecurityUser();
        securityUser.setCurrentUserInfo(curUser);
        securityUser.setPermissionValueList(permissionValueList);

        return securityUser;
    }
}
